// 全局JavaScript函数

// 格式化时间
function formatTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 格式化金额
function formatCurrency(amount) {
    return '¥' + parseFloat(amount).toFixed(2);
}

// 显示加载状态
function showLoading(element) {
    $(element).html('<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">加载中...</span></div></div>');
}

// 显示消息
function showMessage(message, type = 'info') {
    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    };
    
    const html = `
        <div class="alert ${alertClass[type]} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('main').prepend(html);
    
    // 3秒后自动消失
    setTimeout(() => {
        $('.alert').fadeOut();
    }, 3000);
}

// 验证车牌号格式
function validateLicensePlate(plate) {
    // 中国车牌号格式验证
    const regex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/;
    return regex.test(plate.toUpperCase());
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 页面加载完成后的初始化
$(document).ready(function() {
    // 为所有表单添加提交动画
    $('form').on('submit', function() {
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<span class="spinner-border spinner-border-sm" role="status"></span> 处理中...');
        submitBtn.prop('disabled', true);
        
        setTimeout(() => {
            submitBtn.html(originalText);
            submitBtn.prop('disabled', false);
        }, 2000);
    });
    
    // 车牌号输入自动大写
    $('input[id*="license"], input[id*="License"]').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // 数字输入限制
    $('input[type="number"]').on('input', function() {
        if (this.value < 0) this.value = 0;
    });
});

// 导出到全局作用域
window.ParkingApp = {
    formatTime,
    formatCurrency,
    showLoading,
    showMessage,
    validateLicensePlate,
    debounce
};
